package com.webinsky.persist.dao.resource;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.webinsky.common.utils.db.BasicSqlProvider;
import com.webinsky.common.utils.db.PageHelper;
import com.webinsky.common.utils.db.SQLBuilder;
import com.webinsky.persist.entity.resource.ImageFilter;

public class ImageProvider extends BasicSqlProvider {

	private String[] cols = new String[]{"id", "name", "site_id", "file_name", "del", "create_at", "update_at", "language"};
	private String[] countCols = new String[]{"count(*)"};
	
	public ImageProvider() {
		super("image");
	}
	
	private String getSQLByFilter(ImageFilter filter, SQLBuilder sqlBuilder){
		sqlBuilder.WHERE("del = 0");
		if ( filter.getSiteId() > 0 ) {
			sqlBuilder.WHERE(" site_id = " + filter.getSiteId());
		}
		if ( filter.getLang() != null ){
			sqlBuilder.WHERE(" language = '" + filter.getLang() + "'");
		}
		if ( filter.getName() != null ){
			sqlBuilder.WHERE(" file_name like '%" + filter.getName() + "%'");
		}
		if ( !filter.getOrders().isEmpty() ){
			List<String> strOders = new ArrayList<>();
			filter.getOrders().forEach(e -> {
				strOders.add(e.getFieldName() + (e.getIsAscOrDes() ? " asc " : " desc "));				
			});
			if ( !strOders.isEmpty() ){
				String strOrderSQL = String.join(",", strOders);
				sqlBuilder.ORDER_BY(strOrderSQL);
			}
		}
		return sqlBuilder.toString();
	}
	
	
	public String selectByPagnation(Map<String, Object> param){
		ImageFilter filter = (ImageFilter)param.get("filter");
		SQLBuilder sqlBuilder = getSelectBuilder(cols);
		int pageStart = filter.getPageStart();
		int pageSize = filter.getPageSize();
		String pageSQL = PageHelper.startPage(getSQLByFilter(filter, sqlBuilder), pageStart, pageSize);
		return pageSQL;
	}
	
	public String selectCountByPagnation(Map<String, Object> param){
		ImageFilter filter = (ImageFilter)param.get("filter");
		SQLBuilder sqlBuilder = getSelectBuilder(countCols);
		sqlBuilder.WHERE("del = 0");
		if ( filter.getSiteId() > 0 ) {
			sqlBuilder.WHERE(" site_id = " + filter.getSiteId());
		}
		if ( filter.getLang() != null ){
			sqlBuilder.WHERE(" language = '" + filter.getLang() + "'");
		}
		if ( filter.getName() != null ){
			sqlBuilder.WHERE(" name like '%" + filter.getName() + "%'");
		}
		return getSQLByFilter(filter, sqlBuilder);
	}

	@SuppressWarnings("unchecked")
	public String selectByIds(Map<String, Object> param){
		List<Integer> ids = (List<Integer>)param.get("ids");
		SQLBuilder sqlBuilder = getSelectBuilder(cols);
		if ( ids != null && !ids.isEmpty() ){
			List<String> strIds = ids.stream().map(e -> e.toString()).collect(Collectors.toList());
			sqlBuilder.WHERE(" id in (" + String.join(",", strIds) + ")");
		}
		return sqlBuilder.toString();
	}
	
}
